package com.hoperun.product.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.honeywell.aidc.BarcodeFailureEvent
import com.honeywell.aidc.BarcodeReadEvent
import com.honeywell.aidc.BarcodeReader
import com.hoperun.distributecloth.R
import com.hoperun.product.base.BaseActivity
import com.hoperun.product.base.BaseEntity
import com.hoperun.product.entity.BoundInfoEntity
import com.hoperun.product.net.IServiceImpl
import com.hoperun.product.net.RequestServiceImpl
import com.hoperun.product.view.SimpleDialog
import kotlinx.android.synthetic.main.activity_out_bound_layout.*
import kotlinx.android.synthetic.main.activity_return_bound_layout.*
import kotlinx.android.synthetic.main.activity_return_bound_layout.backBtn
import kotlinx.android.synthetic.main.activity_return_bound_layout.boundInfoTv
import kotlinx.android.synthetic.main.activity_return_bound_layout.whlocNoEt

import org.jetbrains.anko.sdk27.coroutines.onClick


/**
 * 回库
 */
class ReturnBoundActivity : BaseActivity(), BarcodeReader.BarcodeListener {
    var isJudgeSuccess = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_return_bound_layout)
        initView()
    }

    fun initView() {
        backBtn.onClick { finish() }
        //回库
        returnBtn.onClick { startReturnboundConfirm() }
        //释放
        releaseBtn.onClick { startUnlockWhloc() }

        whlocNoEt.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
            if (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
                startGetReturnboundData()
                return@OnKeyListener true
            }
            false
        })
        whlocNoEt.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                isJudgeSuccess = false
                //库位需要重新校验
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })
        weightEt.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s.toString().contains(".")) {
                    //保留小數點後兩位
                    if (s.toString().length - s.toString().indexOf(".") > 3) {
                        weightEt.setText(s.toString().substring(0, s.toString().length - 1))
                        weightEt.setSelection(weightEt.text.length)
                    }

                }else{
                    //最大六位整数
                    if (s.toString().length  > 6) {
                        weightEt.setText(s.toString().substring(0, s.toString().length - 1))
                        weightEt.setSelection(weightEt.text.length)
                    }
                }
            }
        })
    }


    /**
     * 获取配送区库位原料信息接口
     */
    fun startGetReturnboundData() {
        val whlocNo = whlocNoEt.text.toString().trim()
        if (whlocNo.isEmpty()) {
            ToastUtils.showLong("请输入库位！")
            return
        }
        showWait()
        RequestServiceImpl.getReturnboundData(mMIPHandler, IServiceImpl.getReturnboundData, whlocNo)
    }


    /**
     * 回库
     */
    fun startReturnboundConfirm() {
        if (!isJudgeSuccess) {
            ToastUtils.showLong("请先校验库位信息！")
            return
        }
        val whlocNo = whlocNoEt.text.toString().trim()

        val weight = weightEt.text.toString().trim()
        if (weight.isEmpty()) {
            ToastUtils.showLong("请输入重量！")
            return
        }

        val boxnum = boxnumEt.text.toString().trim()
        if (boxnum.isEmpty()) {
            ToastUtils.showLong("请输入箱数！")
            return
        }
        showWait()
        RequestServiceImpl.returnboundConfirm(
            mMIPHandler,
            IServiceImpl.returnboundConfirm,
            whlocNo,
            boxnum,
            weight
        )
    }


    /**
     * 释放
     */
    fun startUnlockWhloc() {
        if (!isJudgeSuccess) {
            ToastUtils.showLong("请先校验库位信息！")
            return
        }
        val whlocNo = whlocNoEt.text.toString().trim()
        showWait()
        RequestServiceImpl.unlockWhloc(mMIPHandler, IServiceImpl.unlockWhloc, whlocNo)
    }


    /**
     * 霍尼韦尔扫码监听
     */
    override fun onBarcodeEvent(event: BarcodeReadEvent?) {
        runOnUiThread {
//            val codeDate = event?.getBarcodeData()
//            if (!TextUtils.isEmpty(codeDate)) {
//
//                if (whlocNoEt.hasFocus()) {
//                    whlocNoEt.setText(codeDate)
//                    startGetReturnboundData()
//                }
//            }
        }
    }

    override fun onFailureEvent(event: BarcodeFailureEvent?) {
        runOnUiThread {
            toast("onTriggerEvent")
        }

    }

    override fun onPostHandle(requestType: Int, objBody: Any?, error: Boolean) {


        if (error) {
            when (requestType) {
                IServiceImpl.getReturnboundData -> {
                    val result = GsonUtils.fromJson(objBody.toString(), BoundInfoEntity::class.java)
                    if (result.OPT_FLAG == "SUCCESS") {
                        //校验成功
                        isJudgeSuccess = true
                        boundInfoTv.text =
                            result.DATA?.SZQC + "\n" + result.DATA?.CD + "\n" + result.DATA?.BATCHNO
                        weightEt.setText(result.DATA?.WEIGHT)
                        boxnumEt.setText(result.DATA?.BOXNUM)
                        ToastUtils.showLong(result.MSG_INFO)
                    } else {
                        boundInfoTv.text = ""
                        weightEt.setText("")
                        boxnumEt.setText("")
                        ToastUtils.showLong(result.MSG_INFO)
                    }
                }
                IServiceImpl.returnboundConfirm -> {
                    val result = GsonUtils.fromJson(objBody.toString(), BaseEntity::class.java)
                    if (result.OPT_FLAG == "SUCCESS") {
                        //成功后清空页面数据
                        whlocNoEt.setText("")
                        boundInfoTv.setText("")
                        weightEt.setText("")
                        boxnumEt.setText("")
                        SimpleDialog.show(this, result.MSG_INFO)
                    } else {
                        SimpleDialog.show(this, result.MSG_INFO)
                    }
                }

                IServiceImpl.unlockWhloc -> {
                    val result = GsonUtils.fromJson(objBody.toString(), BaseEntity::class.java)
                    if (result.OPT_FLAG == "SUCCESS") {
                        //成功后清空页面数据
                        whlocNoEt.setText("")
                        boundInfoTv.setText("")
                        weightEt.setText("")
                        boxnumEt.setText("")
                        SimpleDialog.show(this, result.MSG_INFO)
                    } else {
                        SimpleDialog.show(this, result.MSG_INFO)
                    }
                }

            }
        } else {
            ToastUtils.showLong(objBody.toString())
        }
        stopWait()


    }


    /************************************霍尼韦尔***************************************/
    private val ACTION_BARCODE_DATA = "com.honeywell.sample.action.BARCODE_DATA"
    private val ACTION_CLAIM_SCANNER = "com.honeywell.aidc.action.ACTION_CLAIM_SCANNER"
    private val ACTION_RELEASE_SCANNER = "com.honeywell.aidc.action.ACTION_RELEASE_SCANNER"
    private val EXTRA_SCANNER = "com.honeywell.aidc.extra.EXTRA_SCANNER"
    private val EXTRA_PROFILE = "com.honeywell.aidc.extra.EXTRA_PROFILE"
    private val EXTRA_PROPERTIES = "com.honeywell.aidc.extra.EXTRA_PROPERTIES"
    private val barcodeDataReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (ACTION_BARCODE_DATA == intent.action) {
                val version = intent.getIntExtra("version", 0)
                if (version >= 1) {
                    val data = intent.getStringExtra("data")
                   // ToastUtils.showLong("接收到霍尼韦尔广播数据")

                    whlocNoEt.setText(data)
                    startGetReturnboundData()
                }


            }
        }
    }
    private fun claimScanner() {
        val properties = Bundle()

        properties.putBoolean("DPR_DATA_INTENT", true)
        properties.putString("DPR_DATA_INTENT_ACTION", ACTION_BARCODE_DATA)

        sendBroadcast(
            Intent(ACTION_CLAIM_SCANNER).putExtra(
                EXTRA_SCANNER,
                "dcs.scanner.imager"
            ).putExtra(EXTRA_PROFILE, "MyProfile1").putExtra(EXTRA_PROPERTIES, properties)
        )
    }

    private fun releaseScanner() {
        sendBroadcast(Intent(ACTION_RELEASE_SCANNER))
    }
    override fun onResume() {
        super.onResume()
        registerReceiver(barcodeDataReceiver, IntentFilter(ACTION_BARCODE_DATA))
        claimScanner()
    }

    override fun onPause() {
        super.onPause()
        unregisterReceiver(barcodeDataReceiver)
        releaseScanner()
    }
    /************************************霍尼韦尔***************************************/
}